package assignment12;

import java.util.*;

public class MovieStore {
	private Hashtable<String, Movie> movieList; //电影标题 --- 电影对象
	private Hashtable<String, Vector<Movie>> actorList, typeList; //演员名/类型名 --- 电影对象的集合

	//get方法
	public Hashtable<String, Movie> getMovieList() { return movieList; } 
    public Hashtable<String, Vector<Movie>> getActorList() { return actorList; } 
    public Hashtable<String, Vector<Movie>> getTypeList() { return typeList; } 
	
    public MovieStore() { 
		movieList = new Hashtable<String, Movie>(); 
        actorList = new Hashtable<String, Vector<Movie>>(); 
        typeList  = new Hashtable<String, Vector<Movie>>(); 
    } 
	
    //商店中所有电影数
    public String toString() { 
        return ("MovieStore with " + movieList.size() + " movies."); 
    }    
	
    //添加电影
    public void addMovie(Movie aMovie) { 
		//直接put进movieList
    	movieList.put(aMovie.getTitle(), aMovie); 
    	//如果typeList中没有该类型的电影, 添加该类的Vector集合
		if (!typeList.containsKey(aMovie.getType())) 
			typeList.put(aMovie.getType(), new Vector<Movie>());                        
		//向typeList中add对象
		typeList.get(aMovie.getType()).add(aMovie);
		//给aMovie中所有的演员添加该电影对象
	    for (String actor : aMovie.getActors()) {
	    	//如果没有这个演员, 为他创建Vector集合
	    	if (!actorList.containsKey(actor)) {
	    		actorList.put(actor, new Vector<Movie>()); 	    		
	    	}
	    	//向该Vector集合中添加aMovie
	    	actorList.get(actor).add(aMovie); 
	    }
	}
	
    //按Movie对象删除电影
    private void removeMovie(Movie aMovie) {
    	//按标题删除
    	movieList.remove(aMovie.getTitle());
    	//删除typeList该类集合中的电影对象
	    typeList.get(aMovie.getType()).remove(aMovie);
	    //如果删完了, 这个类型也没有存在的必要了
	    if (typeList.get(aMovie.getType()).isEmpty())
	    	typeList.remove(aMovie.getType());
		//给aMovie中所有的演员删除该电影对象
	    for (String actor : aMovie.getActors()) {
	    	//删除该演员的电影列表中的aMovie
	    	actorList.get(actor).remove(aMovie);
	    	//如果删完了就把演员也删了
	    	if(actorList.get(actor).isEmpty()) {
	    		actorList.remove(actor);
	    	}
	    }
	}
    
    //按标题删除电影
	public boolean removeMovie(String aTitle) { 
		if (movieList.get(aTitle) == null) {
			System.out.println("No movie with that title");
			return false;
		}
		Movie aMovie = movieList.get(aTitle);
		removeMovie(aMovie);
		System.out.println(aMovie + "已删除");
		return true;
	}
	
	//列出所有电影名
	public void listMovies() { 
		Enumeration<String> titles = movieList.keys(); 
		while(titles.hasMoreElements()) //还有元素
			//打印当前元素并移到下一个元素
			System.out.println(titles.nextElement()); 
	}
	
	//列出该演员的所有电影
	public void listMoviesWithActor(String anActor) {
		Enumeration<Movie> someMovies = actorList.get(anActor).elements(); 
		while(someMovies.hasMoreElements()) 
			System.out.println(someMovies.nextElement()); 
	}
	
	//列出该类型的所有电影
	public void listMoviesOfType(String aType) { 
		Enumeration<Movie> someMovies = typeList.get(aType).elements(); 
		while(someMovies.hasMoreElements())
			System.out.println(someMovies.nextElement());
	}
}
